import { Injectable, UnauthorizedException } from "@nestjs/common";
import { UsersService } from "../users/users.service";
import { JwtService } from "@nestjs/jwt";
import { UserDto } from "@business/users/interfaces/user.dto";

@Injectable()
export class AuthService {
    constructor(private usersService: UsersService, private jwtService: JwtService) { }

      async signIn(username: string, password: string): Promise<{ accessToken: string; user: UserDto }> {
        const user = await this.usersService.findUserByUsername(username);
        if (user?.password !== password) {
            throw new UnauthorizedException("用户名或密码错误");
        }
        const payload = {
            sub: user.id,
            username: user.username,
            roles: ['admin','user'],
        };
        // secret 已经在 JwtModule 中注册为全局模块, 所以这里可以直接使用
        return { accessToken: await this.jwtService.signAsync(payload),user};
    }

    async findUsers(){
        return await this.usersService.findAllWithConvert();
    }
}
